Announcing Java SDK Generation Support in Amazon API Gateway

Announcing Java SDK Generation Support in Amazon API GatewayMore Info

We are pleased to share the introduction of Java SDK generation support for services managed through Amazon API Gateway. The generated SDKs are compatible with Java 8 and newer versions. They come equipped with robust features such as API key management, customizable authentication options including AWS Identity and Access Management (IAM), automatic retry mechanisms, exception handling, and more. In this article, we will guide you through the process of creating a sample API, generating a Java SDK from it, and examining the various features of the generated SDK. Familiarity with API Gateway concepts is assumed.

Creating a Sample API

To kick things off, let’s create a simple API using the API Gateway console. Head over to the API Gateway console, select your preferred region, and click on Create API. Then, opt for the Example API option and choose Import to set up the example API.

This example API is straightforward, featuring four operations:

  • A GET request on the root resource that returns HTML describing the API.
  • A GET request on the /pets resource, which returns a list of pets.
  • A POST request on the /pets resource for creating a new pet.
  • A GET request on the /pets/{petId} resource that retrieves a specific pet by its ID.

Deploying the API

Next, you’ll deploy the API to a stage. Under Actions, select Deploy API, name the stage test, and click Deploy.

Once the API is deployed, navigate to the SDK Generation tab, select Java as the platform, enter PetStore for the Service Name, and com.petstore.client for the Java Package Name. Leave other fields empty, then choose Generate SDK and download the SDK package, unzipping it afterward.

There are several configuration options available for the Java platform, including:

  • Service Name: This will be the name of the Java Interface for API calls.
  • Java Package Name: This specifies the package under which the generated SDK code will reside, often based on your organization.

The additional optional parameters for publishing the SDK to a remote repository like Maven Central include:

  • Java Build System: Choose either Maven or Gradle, with Maven set as the default.
  • Java Group ID: This typically identifies your organization, defaulting to the Java Package Name if not provided.
  • Java Artifact ID: Identifies the library or product, defaulting to the Service Name if not specified.
  • Java Artifact Version: A version identifier for the published SDK, defaulting to 1.0-SNAPSHOT if not specified.

Compiling the Client

Navigate to the directory where you unzipped the SDK package. Assuming you’ve followed the example, the package should be configured as a Maven project. Ensure that Maven and a JDK have been installed properly, then run the following command to install the client package into your local Maven repository, making it accessible for other local projects:

mvn install

Setting Up an Application

Next, you’ll set up an application that depends on the client package you just installed. As the client requires Java 8 or later, any application that uses the client must be built with Java 8. We will utilize a simple Maven Archetype to create an empty Java 8 project:

mvn archetype:generate -B -DarchetypeGroupId=pl.org.miki -DarchetypeArtifactId=java8-quickstart-archetype -DarchetypeVersion=1.0.0 
    -DgroupId=com.petstore.app 
    -DartifactId=petstore-app 
    -Dversion=1.0 
    -Dpackage=com.petstore.app

Open the newly created project and edit the pom.xml file. Insert the following snippet within the <dependencies> section of the XML file. If you modified any SDK export parameters in the console, replace those values accordingly:

<dependency>
    <groupId>com.petstore.client</groupId>
    <artifactId>PetStore</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

Create a file at src/main/java/com/petstore/app/AppMain.java with the following content:

package com.petstore.app;

import com.petstore.client.*;
import com.petstore.client.model.*;
import com.amazonaws.opensdk.*;
import com.amazonaws.opensdk.config.*;

public class AppMain {
    public static void main(String[] args) {
        // Code to execute
    }
}

Build the application to confirm everything is set up correctly:

mvn install

To execute the application, use the following Maven command. Remember to run mvn install again after making changes before executing:

mvn exec:java -Dexec.mainClass="com.petstore.app.AppMain"

Exploring the SDK

Creating the Client

The first step is to create an instance of the client. You can do this using the client builder accessed through a static factory method on the client interface. All configuration methods on the builder are optional, except those related to authorization. The following example demonstrates how to obtain a builder instance, customize some configurations, and construct a client. Note that these settings are illustrative and may not be the best practices for service clients.

PetStore client = PetStore.builder()
    .timeoutConfiguration(new TimeoutConfiguration()
        .httpRequestTimeout(20_000)
        .totalExecutionTimeout(30_000))
    .connectionConfiguration(new ConnectionConfiguration()
        .maxConnections(100)
        .connectionMaxIdleMillis(120))
    .build();

The builder provides a range of configuration methods for timeouts, connection management, proxy settings, custom endpoints, and authorization. For comprehensive details on what can be configured, refer to the Javadocs.

Making API Calls

Once your client is built, you’re prepared to initiate an API call. For instance, to retrieve the list of current pets, you can use the following code to print each pet to STDOUT. Each API operation generates a corresponding method on the client interface, named according to the HTTP method and resource path, although this can be overridden as discussed later in this post.

client.getPets(new GetPetsRequest())
    .getPets()
    .forEach(p -> System.out.printf("Pet: %sn", p));

The GET /pets operation includes a query parameter named type, which allows filtering of the returned pets. You can set modeled query parameters and headers on the request object:

client.getPets(new GetPetsRequest().type("dog"))
    .getPets()
    .forEach(p -> System.out.printf("Dog: %sn", p));

Next, let’s create a pet and examine the service’s response. Here’s how to call the POST /pets operation, providing details about the new Pet. The CreatePetResult contains the unmarshalled service response and additional HTTP-level metadata accessible via the sdkResponseMetadata() method.

final CreatePetResult result = client.createPet(
    new CreatePetRequest().newPet(new NewPet()
        .type(PetType.Bird)
        .price(123.45)));
System.out.printf("Response message: %s n", result.getNewPetResponse().getMessage());
System.out.println(result.sdkResponseMetadata().header("Content-Type"));
System.out.println(result.sdkResponseMetadata().requestId());
System.out.println(result.sdkResponseMetadata().httpStatusCode());

The GET /pets/{petId} operation uses a path placeholder to retrieve a specific pet identified by its ID. When calling the SDK, simply supply the ID; the SDK manages the rest.

For additional insights on this topic, you can check out another blog post here. Also, for authoritative information on related matters, visit this resource. Lastly, if you’re interested in enhancing your onboarding experience, this article from Forbes is an excellent resource: How Amazon Reimagined Its Onboarding Experience.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *